/*
 * For com.royal.art
 * Copyright [2015/11/11] By FCHEN
 */
package com.manage.controller;

import com.beans.SysUser;
import com.commons.PwdUtils;
import com.commons.util.CookieUtils;
import com.manage.util.UserUtils;
import com.manage.util.Utils;
import com.manage.common.GlobalVariableNames;
import com.manage.common.security.shiro.session.SessionDAO;
import com.manage.context.GlobalContext;
import com.manage.security.FormAuthenticationFilter;
import com.manage.security.SystemAuthorizingRealm.Principal;
import com.services.DeptService;
import com.services.SysRoleService;
import com.services.SysUserService;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.UnauthorizedException;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;

/**
 * AuthController
 * 用户登录
 *
 * @author FCHEN
 * @date 2015/11/11
 */
@Controller
public class AuthController extends BaseController {

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SessionDAO sessionDAO;
    @Autowired
    private DeptService deptService;
    @Autowired
    private SysRoleService sysRoleService;

    /**
     * 登录
     * <p/>
     * //     * @param account
     * //     * @param pwd
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "${adminPath}/login", method = RequestMethod.GET)
    public String login(HttpServletRequest request, HttpServletResponse response) {
        Principal principal = UserUtils.getPrincipal();
        // 如果已登录，再次访问主页，则退出原账号。
        if (GlobalContext.TRUE.equals(GlobalContext.getProperties("notAllowRefreshIndex"))) {
            CookieUtils.setCookie(response, "LOGINED", "false");
        }

        // 如果已经登录，则跳转到管理首页
        if (principal != null && !principal.isMobileLogin()) {
            return "redirect:" + GlobalContext.getProperties(GlobalVariableNames.BASEPATH) + "/index";
        }
        return "auth/login";
    }

    /**
     * 登录失败，真正登录的POST请求由Filter完成
     */
    @RequestMapping(value = "${adminPath}/login", method = RequestMethod.POST)
    public String loginFail(HttpServletRequest request, HttpServletResponse response, Model model) {
        Principal principal = UserUtils.getPrincipal();
        // 如果已经登录，则跳转到管理首页
        if (principal != null) {
            return "redirect:" + GlobalContext.getProperties(GlobalVariableNames.BASEPATH) + "/index";
        }
        String username = WebUtils.getCleanParam(request, FormAuthenticationFilter.DEFAULT_USERNAME_PARAM);
        boolean rememberMe = WebUtils.isTrue(request, FormAuthenticationFilter.DEFAULT_REMEMBER_ME_PARAM);
        String exception = (String) request.getAttribute(FormAuthenticationFilter.DEFAULT_ERROR_KEY_ATTRIBUTE_NAME);
        String message = (String) request.getAttribute(FormAuthenticationFilter.DEFAULT_MESSAGE_PARAM);

        if (StringUtils.isBlank(message) || StringUtils.equals(message, "null")) {
            message = "用户或密码错误, 请重试.";
        }

        model.addAttribute(FormAuthenticationFilter.DEFAULT_USERNAME_PARAM, username);
        model.addAttribute(FormAuthenticationFilter.DEFAULT_REMEMBER_ME_PARAM, rememberMe);
        model.addAttribute(FormAuthenticationFilter.DEFAULT_ERROR_KEY_ATTRIBUTE_NAME, exception);
        model.addAttribute(FormAuthenticationFilter.DEFAULT_MESSAGE_PARAM, message);

        if (logger.isDebugEnabled()) {
            logger.debug("login fail, active session size: {}, message: {}, exception: {}",
                    sessionDAO.getActiveSessions(false).size(), message, exception);
        }

        // 非授权异常，登录失败，验证码加1。
        if (!UnauthorizedException.class.getName().equals(exception)) {
            model.addAttribute("isValidateCodeLogin", Utils.isValidateCodeLogin(username, true, false));
        }
        return "auth/login";
    }

    /**
     * 查询单个用户信息
     *
     * @param request
     * @return
     */
    @RequiresPermissions("user")
    @RequestMapping("${adminPath}/userOne")
    private String userOne(HttpServletRequest request) {
        SysUser user = UserUtils.getUser();
        request.setAttribute("sysUser", user);
        return "sys/sysuser/editpwd";
    }

    /**
     * 查询单个用户信息
     *
     * @param request
     * @return
     */
    @RequiresPermissions("user")
    @RequestMapping("${adminPath}/userInfo")
    private String userInfo(HttpServletRequest request, String flag) {
        SysUser user = UserUtils.getUser();

        request.setAttribute("storeUrl", UserUtils.storeUrl);
        request.setAttribute("sysUser", user);
        request.setAttribute("user",sysUserService.queryById(user.getUserId()));
        request.setAttribute("dept", deptService.queryById(user.getDeptId()));
        request.setAttribute("role", sysRoleService.queryById(Long.valueOf(user.getUserRole())));

        request.setAttribute("flag", flag);
        return "sys/sysuser/editUser";
    }

    @RequiresPermissions("user")
    @RequestMapping("${adminPath}/modifyUser")
    private String modifyUser(HttpServletRequest request,SysUser sysUser) {
        sysUser.setUpdateBy(UserUtils.getUser().getUserId());

        int flag = sysUserService.modifyUser(sysUser);

        return "redirect:userInfo?flag="+flag+"";
    }


    /**
     * 修改密码
     *
     * @param request
     * @return
     */
    @RequiresPermissions("user")
    @RequestMapping(value = "${adminPath}/updatePwd", method = RequestMethod.POST)
    private String updatePwd(String pwd, String newPwd, HttpServletRequest request) {

        int result = -1;
        SysUser user = UserUtils.getUser();
        if (user != null) {
            if (user.getPassword().equals(PwdUtils.saltPwd(pwd, user.getSalt()))) {
                //相等，进行密码修改
                HashMap<String, String> param = new HashMap<String, String>();
                param.put("account", user.getMobile());
                param.put("pwd", PwdUtils.saltPwd(newPwd, user.getSalt()));//加密后修改数据库密码
                sysUserService.updateUserPwd(param);
                result = 1;//成功
            } else {
                result = -2;//输入密码与数据库密码不相符
            }
        } else {
            result = -3;//用户不存在
        }

        request.setAttribute("resultUp", result);//执行结果
        request.setAttribute("sysUser", user);
        return "sys/sysuser/editpwd";
    }
}
